Ext.define('Seq.grid.Search', {
    extend: 'Ext.form.field.Text',
    xtype: 'xgridsearch',

    maxLength: 40,
    width: 210,
    emptyText: '输入查询条件',
    enableKeyEvents: true,

    config: {
        url: null
    },

    triggers: {
        clear: {
            weight: 0,
            cls: 'x-form-clear-trigger',
            hidden: true,
            handler(cmp, trigger, e) {
                cmp.clear();
            }
        },
        search: {
            weight: 1,
            cls: 'x-form-search-trigger',
            handler(cmp, trigger, e) {
                cmp.search(cmp, trigger, e);
            }
        }
    },

    listeners: {
        keydown(me, e, eOpts) {
            if (e.ENTER == e.getKey()) {
                me.search(me, me.getTrigger('search'), e);
            }
        }
    },

    getGrid: function () {
        var me = this, panel = me.up('panel');
        return panel.isXType('grid') ? panel : panel.down('grid');
    },

    search() {
        let me = this, text = me.getValue();
        if (Ext.isEmpty(text)) {
            me.clear();
        } else {
            me.getTrigger('clear').show();
            if (!Ext.isEmpty(me.getUrl())) {
                me.loadByAjax();
            } else {
                let store = me.getGrid().getStore();
                store.getProxy().getExtraParams().q = text;
                store.reload();
            }
        }
    },

    loadByAjax() {
        let me = this, store = me.getGrid().getStore();
        Seq.Ajax.request({
            url: me.getUrl(),
            params: Ext.apply(store.getProxy().extraParams || {}, {
                q: me.getValue()
            }),
            fnSuccess(options, result) {
                store.loadRawData(result.data.content || result.data);
            }
        })
    },

    clear() {
        let me = this, store = me.getGrid().getStore();
        me.setValue('');
        delete store.getProxy().extraParams.q;
        store.reload();
        me.getTrigger('clear').hide();
    }

});